package com.stepin2it.newstalk;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.content.Context;
import android.util.Log;

public class DataManager
{
	private static final String TAG = "DataManager";
	private static FlickrPhotoResponse responseObject = null;
	/*
	public static List<Photo>  parseFlickrPhotoResponse(Context context, String jsonFileUrl )
	{

		FlickrPhotoResponse fetchPhotosResponse;

		InputStream source = retrieveStream(jsonFileUrl);

		Reader reader = new InputStreamReader(source);

		Gson gson = new Gson();

		Type responseType = new TypeToken<FlickrPhotoResponse>()
		{

		}.getType();

		fetchPhotosResponse = gson.fromJson(reader, responseType);

		// Log.d(TAG, "------photos----" + fetchPhotosResponse.photos.get(0).getId());

		return fetchPhotosResponse.photos;
	}
	*/
	
    public static FlickrPhotoResponse readFlickrPhotoResponse(String jsonFileUrl)
    {
    	Log.d(TAG, "---------------- JSON URL: " + jsonFileUrl);
        InputStream source = retrieveStream(jsonFileUrl);
        
        if(source != null){
        	Log.d(TAG, "InputStream NOT null");
        }
        
        Reader reader = new InputStreamReader(source);
        
        Gson gson = new Gson();
        
        Log.d(TAG, "getting TypeToken");
        Type listType = new TypeToken<FlickrPhotoResponse>()
        {
        }.getType();
        
        Log.d(TAG, "listType is: " + listType.toString());

        responseObject = gson.fromJson(reader, listType);
        
        if(responseObject != null){
        	Log.d(TAG, "responseObject is NOT NULL");
        }
        
        return responseObject;
    }
	private static InputStream retrieveStream(String url)
	{
		DefaultHttpClient client = new DefaultHttpClient();

		HttpGet getRequest = new HttpGet(url);

		try
		{

			HttpResponse getResponse = client.execute(getRequest);
			final int statusCode = getResponse.getStatusLine().getStatusCode();

			if (statusCode != HttpStatus.SC_OK)
			{
				Log.w(TAG, "-----------Statuscode " + statusCode + " for URL " + url);
				return null;
			}

			HttpEntity getResponseEntity = getResponse.getEntity();
			return getResponseEntity.getContent();

		} catch (IOException e)
		{
			getRequest.abort();
			Log.d(TAG, "---------------Error for URL " + e.toString());
		}

		return null;

	}


}
